//
//  PlusSignController.m
//  diaoyuren
//
//  Created by 钓鱼人 on 15/12/18.
//  Copyright © 2015年 game. All rights reserved.

#import "PlusSignController.h"
#import "SelectNavView.h"
#import "FaBuSelect.h"
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import "PersonEditModel.h"
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#import "FabuImageModel.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFURLSessionManager.h"
#define TextviewDefaultHeight SCREEN_HEIGHT*0.2
#define TextviewMaxHeight 120
#define ScrollViewMinContentSize SCREEN_HEIGHT-60
#define ScrollViewContentSizeChange self.height+40+30+100

@interface PlusSignController ()<UIScrollViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,UIScrollViewDelegate,UITextViewDelegate>

@property (nonatomic,strong) SelectNavView *nav;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,assign) NSInteger count;
@property (nonatomic,assign) CGFloat height;
@property (nonatomic,strong) FaBuSelect *footView;
@property (nonatomic,assign) NSInteger wenzi;//记录当前TextView是第几个
@property (nonatomic,assign) NSInteger tupian;//记录当前imageView是第几个
@property (nonatomic,strong) SelectNavView *naV;
@property (nonatomic,strong) UITextField *texeFile;
@property (nonatomic,strong) NSMutableArray *imageAry;
@property (nonatomic,assign) NSInteger textTag;//记录点击的TextView的tag值
@property (nonatomic,assign) CGFloat keboarHight;//记录键盘的高度
@property (nonatomic,assign) CGFloat keyBoardYY;//记录键盘的顶部Y坐标

/**
 *  记录textView 上一次的高度 与textView现在的高度进行对比 判断textView是否是由高变低
 */
@property (nonatomic,assign) CGFloat textViewNowHight;

/**
 *  存储 文字 与 图片二进制数据  用于存草稿
 */
@property (nonatomic,strong) NSMutableArray *dataAry;

/**
 *  存储 图片 二进制数据  用于草稿箱的显示
 */
@property (nonatomic,strong) NSMutableArray *imageDataAry;

/**
 *  存储 文字 二进制数据  用于草稿箱的显示
 */
@property (nonatomic,strong) NSMutableArray *textDataAry;

/**
 *  用于检测点击返回时 是否需要弹出 选择保存的视图
 */
@property (nonatomic,strong) NSMutableArray *backAry;

/**
 *  保存到草稿的数据数组
 */
@property (nonatomic,strong) NSMutableArray *filedImgAry;

/**
 *  发布数组
 */
@property (nonatomic,strong) NSMutableArray *FabuDataAry;
/**
 *  用于上传图片总进度显示的字典
 */
@property (nonatomic,strong) NSMutableDictionary *dic;

@property (nonatomic,assign) NSInteger fabuImageCount;
@property (nonatomic,assign) NSInteger ploadCount;
@property (nonatomic,copy) NSString *plodString;
@property (nonatomic,copy) NSString *formhash;

@property (nonatomic,strong)  UIViewController *appRootViewController;
@property (nonatomic,strong) UIWindow *window;

@property (nonatomic,strong)  UIViewController *topViewController ;//= appRootViewController;

@property (nonatomic,strong) MBProgressHUD *MyHUD;

@property (nonatomic,strong) NSMutableDictionary *attachnewDic;

@property (nonatomic,strong) NSMutableDictionary *imageNameDic;
@end

@implementation PlusSignController

-(NSMutableDictionary *)imageNameDic{
    if (!_imageNameDic) {
        _imageNameDic = [NSMutableDictionary dictionary];
    }
    return _imageNameDic;
}

-(MBProgressHUD *)MyHUD{
    
    if (!_MyHUD) {
        _MyHUD =  [[MBProgressHUD alloc] initWithView:self.view];
        _MyHUD.dimBackground = YES;
        
        [self.topViewController.view addSubview:_MyHUD];
        _MyHUD.mode = MBProgressHUDModeDeterminate;
    }
        return _MyHUD;
}

-(NSMutableDictionary *)attachnewDic{
    if (!_attachnewDic) {
        _attachnewDic = [NSMutableDictionary dictionary];
    }
    return _attachnewDic;
}

-(NSMutableDictionary *)dic{
    if (!_dic) {
        _dic = [NSMutableDictionary dictionary];
    }
    return _dic;
}

-(NSMutableArray *)FabuDataAry{
    if (!_FabuDataAry) {
        _FabuDataAry = [NSMutableArray array];
    }
    return _FabuDataAry;
}

-(NSMutableArray *)textDataAry{
    if (!_textDataAry) {
        _textDataAry = [NSMutableArray array];
    }
    return _textDataAry;
}

-(NSMutableArray *)imageAry{
    if (!_imageAry) {
        _imageAry = [NSMutableArray array];
    }
    return _imageAry;
}

-(NSMutableArray *)dataAry{
    if (!_dataAry) {
        _dataAry = [NSMutableArray array];
    }
    return _dataAry;
}

-(NSMutableArray *)imageDataAry{

    if (!_imageDataAry) {
        _imageDataAry = [NSMutableArray array];
    }
    
    return _imageDataAry;
}

-(NSMutableArray *)backAry{
    if (!_backAry) {
        _backAry = [NSMutableArray array];
    }
    return _backAry;
}

-(NSMutableArray *)filedImgAry{
    if (!_filedImgAry) {
        _filedImgAry = [NSMutableArray array];
    }
    return _filedImgAry;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self CreatNavView];
}
-(void)CreatNavView{
    self.naV = [[SelectNavView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    self.naV.titile.text = @"发帖";
    self.naV.share.titleLabel.font = font(SCREEN_WIDTH*0.05);
    [self.naV.share setTitle:@"发布" forState:UIControlStateNormal];
    self.naV.share.y = 21;
    self.naV.share.x = SCREEN_WIDTH - 60;
    [self.view addSubview:self.naV];
    [self.naV.bacBtn addTarget:self action:@selector(Back) forControlEvents:UIControlEventTouchUpInside];
    [self.naV.share addTarget:self action:@selector(FaBu) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark---最下方的加号
-(FaBuSelect *)footView{
    if (!_footView) {
        
        _footView = [[FaBuSelect alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREEN_HEIGHT*0.063*2)];
        [_footView.wenziBtn addTarget:self action:@selector(WenziClick) forControlEvents:UIControlEventTouchUpInside];
        
        [_footView.tupianBtn addTarget:self action:@selector(Tupian) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _footView;
}


#pragma mark--点击返回时调用 用于检测是否要弹出保存草稿View 点击保存时将数据放到self.dataAry，点击发布 则将内容放到self.FabuDataAry用于发送 更具BOOL值不同来判断执行操作
-(void)DataToEditWhithIsBack:(BOOL)isback AndIsedit:(BOOL)edit AndIsFabu:(BOOL)isfabu{
    
    if (isback) {
          [self.backAry removeAllObjects];
        
        if (self.texeFile.text.length!=0) {
            [self.backAry addObject:self.texeFile.text];
        }
    }
    
    if (edit) {
        [self.dataAry removeAllObjects];

    }
    
    if (isfabu) {
        [self.FabuDataAry removeAllObjects];
    }
  

    for (int i=1; i<self.count+1+10000; i++) {
        
        UIView *view = [self.view viewWithTag:i];
        
        if ([view isKindOfClass:[UITextView class]]) {
            
            UITextView *textView = [self.view viewWithTag:i];
            
            
            if (isback) {
                if (textView.text.length!=0) {
                    if (self.backAry.count==0) {
                        [self.backAry addObject:textView.text];
                    }
                }
            }
            
            if (edit) {
                
                if (textView.text.length!=0) {
                    if (self.textDataAry.count==0) {
                        [self.textDataAry addObject:textView.text];
                    }
                }
                
                 [self.dataAry addObject:textView.text];
            }

            if (isfabu) {
                [self.FabuDataAry addObject:textView.text];
            }
        }
        
        if ([view isKindOfClass:[UIImageView class]]) {
            
            UIImageView *textView = [self.view viewWithTag:i];
            
            UIImage *portraitImg = textView.image;

            if (isback) {
                if (self.backAry.count==0) {
                    [self.backAry addObject:@"Image"];
                }
            }
            if (edit) {
                
               [self.dataAry addObject:UIImageJPEGRepresentation(portraitImg,0.8)];
            }
            
            if (isfabu) {
                
                NSString *ss = [NSString stringWithFormat:@"%ld",(long)self.fabuImageCount];
                NSString *name = [Manager ret8bitString];
                [self.imageNameDic setValue:[NSString stringWithFormat:@"%@.jpg",name] forKey:ss];

                [self.FabuDataAry addObject:[NSString stringWithFormat:@"%@.jpg",name]];
                self.fabuImageCount += 1;
            }
        }
    }
}

#pragma mark---点击发布Action
-(void)FaBu{
    
    self.fabuImageCount = 0;
    self.ploadCount = 0;
    self.plodString = @"";
    
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    [self DataToEditWhithIsBack:NO AndIsedit:NO AndIsFabu:YES];
    
    if (self.texeFile.text.length==0) {
        [Manager GetHudWhithText:@"请输入标题" AndFatherView:self.view];
        
    }else if (self.imageDataAry.count!=0){  //包含图片发送
        [self Goback];
        for (int i=0; i<self.imageDataAry.count; i++) {
            
            NSString *name = [NSString stringWithFormat:@"%d",i];
            
            [self PostImageWhithWhithImageData:self.imageDataAry[i] AndName:[self.imageNameDic valueForKey:name]];
        }
        
    }else{//纯文字发送
        [self Goback];
        [self PostOnlyScript];
    }
}

#pragma mark--返回 自动判断是用 pop 还是 dismiss
-(void)Goback{
    
    NSArray *viewcontrollers=self.navigationController.viewControllers;
    if (viewcontrollers.count>1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {//push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{//present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
#pragma mark--点击返回按钮Action
-(void)Back{
    
    [self DataToEditWhithIsBack:YES AndIsedit:NO AndIsFabu:NO];
    
    if (self.backAry.count==0) {
        [self Goback];
    
    }else{
        
        UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:@"是否保存草稿?" preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *ToPhone = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self Edit];
                    }];
        
        UIAlertAction *ToImage = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
             [self Goback];
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [aler addAction:ToPhone];
        [aler addAction:ToImage];
        [aler addAction:cancel];
        [self presentViewController:aler animated:YES completion:nil];
    }
}
#pragma mark--保存草稿
-(void)Edit{
    [self DataToEditWhithIsBack:NO AndIsedit:YES AndIsFabu:NO];
    
    NSString *name = @"新帖子[新帖]";
    
    if (self.texeFile.text.length!=0) {
        
        name = [NSString stringWithFormat:@"%@[新帖]",self.texeFile.text];
    }
    
    NSString *text;
    
    if (self.textDataAry.count!=0) {
        text = self.textDataAry.firstObject;
    }else{
        text = @"";
    }
    
    NSDictionary *dic = @{
                          @"time":[Manager AchiveNowTime],
                          @"images":self.imageDataAry,
                          @"name":name,
                          @"type":@"PlusUp",
                          @"text":text,
                          @"Id":self.fid,
                          @"heading":self.texeFile.text,
                          @"ImageAndText":self.dataAry,
                          };
    
    self.filedImgAry = [NSMutableArray arrayWithContentsOfFile:[Manager editeFilePath]];
    
    [self.filedImgAry insertObject:dic atIndex:0];
    [self.filedImgAry writeToFile:[Manager editeFilePath] atomically:YES];
    [self.filedImgAry removeAllObjects];
    

    if ([_deleget respondsToSelector:@selector(GetToEdit)]) {
        [self.deleget GetToEdit];
    }
    
    [self Goback];
}

#pragma mark--MD5加密
- (NSString *)md5WhithString:(NSString *)string{
    const char *concat_str = [string UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(concat_str, strlen(concat_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
        [hash appendFormat:@"%02x", result[i]];
    return [hash lowercaseString];
}
#pragma mark--得到Hash值
-(NSString *)getHashWhithUid:(NSString *)uid{

    NSString *md5 = [self md5WhithString:@"4d3222hnJri1ndbP"];
    NSString *subString = [md5 substringFromIndex:8];
    NSString *apendString = [NSString stringWithFormat:@"%@%@",subString,uid];
    NSString *result = [self md5WhithString:apendString];
    return result;
}
#pragma mark--Post图片
-(void)PostImageWhithWhithImageData:(NSData *)imageData AndName:(NSString *)name{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
   AFHTTPRequestOperation *operation = [manager POST:Forumupload parameters:@{@"hash":[self getHashWhithUid:self.app.userModel.uid],@"type":@"image",@"uid":self.app.userModel.uid} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:imageData name:@"Filedata" fileName:name mimeType:@"application/octet-stream"];
        
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            
            FabuImageModel *model =[[FabuImageModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
            self.formhash = model.formhash;
            
            for (NSString *name in self.FabuDataAry) {
                
                if ([name isEqualToString:model.file_name]) {
                    
                    NSInteger Index = [self.FabuDataAry indexOfObject:name];
                    NSString *ss = [NSString stringWithFormat:@"[attach]%@[/attach]",model.aid];
                    [self.FabuDataAry replaceObjectAtIndex:Index withObject:ss];
                    break;
                }
            }
            
            
            NSString *attt = [NSString stringWithFormat:@"attachnew[%@][description]",model.aid];
            [self.attachnewDic setValue:@"" forKey:attt];

            self.ploadCount += 1;
            if (self.ploadCount == self.imageDataAry.count) {
                
                for (NSString *name in self.FabuDataAry) {
                    
                    if ([name rangeOfString:@"[attach]"].length!=0) {
                        self.plodString = [self.plodString stringByAppendingString:name];
                    }else{
                     self.plodString = [self.plodString stringByAppendingString:[NSString stringWithFormat:@"%@\n",name]];
                    }
                }

                [self PostNewthreadWhithFormhash:self.formhash];
            }

        }else{
            
            [self.MyHUD hide:YES];
            [self.MyHUD removeFromSuperview];
            [Manager GetHudWhithText:@"发送失败" AndFatherView:self.topViewController.view];
            [self Edit];
            
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self.MyHUD hide:YES];
        [self.MyHUD removeFromSuperview];
        [Manager GetHudWhithText:@"发送失败" AndFatherView:self.topViewController.view];
         [self Edit];
        
    }];
    
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        
        float p = (float)totalBytesWritten / totalBytesExpectedToWrite;
        
        [self.dic setValue:[NSString stringWithFormat:@"%f",p] forKey:name];
        
        __block CGFloat  ffff ;
        [self.dic enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            
            ffff += [obj floatValue];
            
        }];
        
    
        self.MyHUD.labelText = [NSString stringWithFormat:@"%.f%%",(ffff/self.imageDataAry.count)*100];
        
        self.MyHUD.progress = ffff/self.imageDataAry.count;
        
        [self.MyHUD show:YES];

        if ((ffff/self.imageDataAry.count)==1) {
            [self.MyHUD hide:YES];
            [self.MyHUD removeFromSuperview];
            
        }
 
    }];
}

#pragma mark--上传完图片 执行发帖操作，如果是纯文字直接进行发帖
-(void)PostNewthreadWhithFormhash:(NSString *)formhash{

    NSString *local = [NSString stringWithFormat:@"%@|%@|%@",[self.Myud valueForKey:@"longitude"],[self.Myud valueForKey:@"latitude"],[self.Myud valueForKey:@"localName"]];
    
    
    NSLog(@"%@",local);
    NSDictionary *dic = @{
                          @"fid":self.fid,
                          @"subject":self.texeFile.text,
                          @"message":self.plodString,
                          @"formhash":formhash,
                          @"location":local,
                          };
    
    NSMutableDictionary *upDic = [NSMutableDictionary dictionary];
    [upDic addEntriesFromDictionary:dic];
    [upDic addEntriesFromDictionary:self.attachnewDic];

    [[Manager sharedManager]ResponseWhithURL:Newthread AndParameter:upDic AndCompletionType:^(id responseObject, DIEError *error) {
        
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
        
            [Manager GetHudWhithText:@"提交成功" AndFatherView:self.topViewController.view];
        }
        if ([responseObject[@"code"] integerValue]!=200||error) {//发送失败
            [Manager GetHudWhithText:@"发送失败" AndFatherView:self.topViewController.view];
             [self Edit];
        }
    }];
}
#pragma mark--如果只有纯文字，则调用该操作
-(void)PostOnlyScript{
    
    for (NSString *name in self.FabuDataAry) {
        self.plodString = [self.plodString stringByAppendingString:[NSString stringWithFormat:@"%@\n",name]];
    }

 [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
        
            [self PostNewthreadWhithFormhash:responseObject[@"data"][@"formhash"]];
        }else{
        
            [Manager GetHudWhithText:@"发送失败" AndFatherView:self.topViewController.view];
             [self Edit];

        }
    }];
}
#pragma mark---早草稿箱点击重发会调用此方法
-(void)setAnew:(NSString *)Anew{
    _Anew = Anew;
    [self FaBu];
}
#pragma mark--草稿箱 重写
-(void)setEditDic:(NSDictionary *)editDic{
    _editDic = editDic;
    
    PersonEditModel *model = [[PersonEditModel alloc]initWithDictionary:_editDic error:nil];
    
    [self.imageDataAry addObjectsFromArray: model.images];
    //先删除自建的第一个TextView
    UIButton *btn = [self.view viewWithTag:10000+1+100];
    [self click:btn];
    
    NSArray *ary = model.ImageAndText;
    
    if (ary.count!=0) {
        
        for (int i=0; i<ary.count; i++) {
            NSString *class = ary[i];
            
            if ([class isKindOfClass:[NSData class]]) {
                
                [self CreatImageViewWhirhImage:[UIImage imageWithData:ary[i]]];
            }
            
            if ([class isKindOfClass:[NSString class]]) {
                
                [self CreatTextViewWhthText:class];
            }
        }
    }
    
    self.texeFile.text = model.heading;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    
    _scrollView.bounces = YES;
    [self.scrollView addSubview:self.footView];
    [self CreattextField];
    [self CreatTextViewWhthText:@""];//自建一个textview
 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];//在这里注册通知  观察键盘变化
    
        self.window = [UIApplication sharedApplication].keyWindow;
        self.appRootViewController = self.window.rootViewController;
        self.topViewController = self.appRootViewController;
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];// 键盘的frame
    
    self.keboarHight = keyboardF.size.height;
    self.keyBoardYY= keyboardF.origin.y;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
        UIView *view = [self.view viewWithTag:self.textTag];
        
        CGPoint point = [view convertPoint:CGPointZero toView:self.view];//获取textView在self.View上的位置 textView是add在scrollView上的
        
        CGFloat jianjian = keyboardF.origin.y-(point.y+view.height);
       
        [UIView animateWithDuration:duration animations:^{
            if (jianjian<0) {//当点击的textView底边低于键盘时
                
            self.scrollView.contentOffset =  CGPointMake(0, view.y-(SCREEN_HEIGHT-H(view)-keyboardF.size.height-64-10));
            }

            if (point.y<64) {//当点击的textView顶部高于导航栏时
            self.scrollView.contentOffset = CGPointMake(0, view.y-10);
      
            }
            
            if (keyboardF.origin.y==SCREEN_HEIGHT) {//如果键盘隐藏
                self.scrollView.y =  64;
                self.scrollView.height =  SCREEN_HEIGHT-64;
                [self ScrollViewContSizeMake];
            }
        }];
    });
}

#pragma mark---建立标题
-(void)CreattextField{
    _texeFile = [[UITextField alloc]initWithFrame:CGRectMake(10, _height+10, SCREEN_WIDTH-20, SCREEN_HEIGHT*0.07)];
    
    self.height =  Height(_texeFile);
    
    self.scrollView.contentSize = CGSizeMake(0, self.height+40+30);
    
    _texeFile.borderStyle = 3;
    
    _texeFile.font =font(SCREEN_WIDTH*0.04);
     _texeFile.placeholder = @"请填写标题或简单描述...";
    [self.scrollView addSubview:_texeFile];
}

#pragma mark---点击文字 创建textView
-(void)WenziClick{
    [self CreatTextViewWhthText:@""];
}
/**
 *  添加  图片
 */
-(void)Tupian{
    if ([Manager isPhotoLibraryAvailable]) {
        
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
            imagePickerVc.allowPickingVideo = NO;
            imagePickerVc.allowPickingOriginalPhoto = NO;
            [self presentViewController:imagePickerVc animated:YES completion:nil];
    }

}

#pragma mark TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{

    for (int i=0; i<photos.count; i++) {
        
        [self CreatImageViewWhirhImage:[UIImage imageWithData:UIImageJPEGRepresentation(photos[i],0.1)]];
        
        UIImage *image = [Manager imageCompressForWidth:photos[i] targetWidth:800];
        [self.imageDataAry addObject: UIImageJPEGRepresentation(image,0.8)];
    }
}


#pragma mark---相册相机回调协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
    [self CreatImageViewWhirhImage:[UIImage imageWithData:UIImageJPEGRepresentation(portraitImg,0.1)]];
    
    UIImage *image = [Manager imageCompressForWidth:portraitImg targetWidth:800];
    [self.imageDataAry addObject: UIImageJPEGRepresentation(image,0.8)];
    [picker dismissViewControllerAnimated:YES completion:nil];//关闭相册界面
}

/**
 *  添加 文字VIew
 */
-(void)CreatTextViewWhthText:(NSString *)string{
    
    self.count += 1;
    UITextView *text = [[UITextView alloc]initWithFrame:CGRectMake(10, _height+10, SCREEN_WIDTH-20, 0)];
    
    text.layer.borderColor = [UIColor lightGrayColor].CGColor;
    text.layer.borderWidth = 0.5;
    
    text.tag = self.count+10000;
    text.delegate = self;
    
    text.font = font(SCREEN_WIDTH*0.045);
    
    [self.scrollView addSubview:text];
    
    //根据文字动态计算高度
    text.text = string;
    CGRect textViewFrame = text.frame;
    CGSize textSize = [text sizeThatFits:CGSizeMake(CGRectGetWidth(textViewFrame), 1000.0f)];
    
    CGFloat offset = 10;
    text.scrollEnabled = (textSize.height > TextviewMaxHeight-offset);
    textViewFrame.size.height = MAX(TextviewDefaultHeight, MIN(textSize.height, textSize.height));
    text.frame = textViewFrame;
    

    UIButton *bnt = [UIButton buttonWithType:UIButtonTypeCustom];
    [bnt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    bnt.frame = CGRectMake(W(text)-55, H(text)-35, 50, 30);

    bnt.tag = text.tag+100;
    bnt.titleLabel.font = [UIFont boldSystemFontOfSize:SCREEN_WIDTH*0.04];
    bnt.backgroundColor = RGBA(253, 166, 142, 0.6);

    [bnt setTitle:@"删除" forState:UIControlStateNormal];
    
    [bnt addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [text addSubview:bnt];
      radius(bnt, 15);
   
    self.height =  Height(text);
    self.footView.y = self.height+10;
    [self ScrollViewContSizeMake];
}


-(void)CreatImageViewWhirhImage:(UIImage *)image{
    self.count += 1;

    UIImage *bbImage = [Manager imageByScalingToMaxSize:image WhithMAXWIdth:SCREEN_WIDTH-20];
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[Manager imageCompressForWidth:image targetWidth:800]];
    
    imageView.frame = CGRectMake(10, self.height+10, self.view.frame.size.width-20, bbImage.size.height);
    
    imageView.userInteractionEnabled = YES;
    
    [self.scrollView addSubview:imageView];
    
    imageView.tag = self.count+10000;
    
    UIButton *bnt = [UIButton buttonWithType:UIButtonTypeSystem];
    
    bnt.tag = imageView.tag+100;
    
    [bnt setTitle:@"删除" forState:UIControlStateNormal];
    
    [bnt setTitleColor:mainColor forState:UIControlStateNormal];
    bnt.frame = CGRectMake(W(imageView)-55, H(imageView)-35, 50, 30);

    bnt.titleLabel.font = [UIFont boldSystemFontOfSize:SCREEN_WIDTH*0.04];
    bnt.backgroundColor = RGBA(253, 166, 142, 0.6);
     radius(bnt, 15);
    
    [bnt addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
    [imageView addSubview:bnt];
    
    self.height =  Height(imageView);
    self.scrollView.contentSize = CGSizeMake(0, ScrollViewContentSizeChange);
    self.footView.y = self.height+10;
}

-(void)ScrollViewContSizeMake{
    self.scrollView.contentSize = CGSizeMake(0, ScrollViewContentSizeChange);
    
    if (self.height+40+30<ScrollViewMinContentSize) {
        self.scrollView.contentSize = CGSizeMake(0, ScrollViewMinContentSize);
    }
}

/**
 * textView代理方法
 *
 *  作用  让textView的高度随文字内容的高度而变化  同时将textView 下面的视图往下移
 */
-(void)textViewDidChange:(UITextView *)textView{

    CGRect textViewFrame = textView.frame;
    CGSize textSize = [textView sizeThatFits:CGSizeMake(CGRectGetWidth(textViewFrame), 1000.0f)];
    
    CGFloat offset = 10;
    textView.scrollEnabled = (textSize.height > TextviewMaxHeight-offset);
    textViewFrame.size.height = MAX(TextviewDefaultHeight, MIN(textSize.height, textSize.height));
    textView.frame = textViewFrame;

    UIButton *btn = [self.view viewWithTag:textView.tag+100];
    btn.frame = CGRectMake(W(textView)-55, H(textView)-35, 50, 30);
    
    
    CGPoint point = [textView convertPoint:CGPointZero toView:self.view];

    /**
     * textView随内容变高后 判断其底边Y坐标是否小于键盘的顶部Y坐标  所以要往上提 偏移量增加 让更大的Y位置滚到基准线位置
     *
     *  到 textView的高度变短时 要让textView的底边还是处于键盘的top位置 就要往下走 所以就要减小偏移量 当偏移量小于0时就等于0
     *
     */
    CGFloat jianjian = self.keyBoardYY-(point.y+textViewFrame.size.height);
    
     CGFloat cha = self.textViewNowHight-H(textView);//textView前后高度的差值 大于0则代表前一次比后一次高，textView在变短
    
        if (jianjian<0||cha>0) {
            
            self.scrollView.contentOffset =  CGPointMake(0, (textViewFrame.origin.y+textViewFrame.size.height)-(SCREEN_HEIGHT- self.keboarHight-64-10));
            
            if ( self.scrollView.contentOffset.y<0) {
                self.scrollView.contentOffset =  CGPointMake(0, 0);
            }
            
        }
  
            for (int i = (int)textView.tag; i<self.count+10000+1; i++) {
    
                UIView *view = [self.view viewWithTag:i];
    
                if (view.tag!=textView.tag) {
    
                    UIView *fronview = [self.view viewWithTag:i-1];
                    view.y = Height(fronview)+10;
                }
                self.height =  Height(view);
            }

            self.footView.y = self.height+10;
            self.textViewNowHight = H(textView);
}

-(void)textViewDidBeginEditing:(UITextView *)textView{
    self.textTag = textView.tag;
}

/**
 *
 */
#pragma mark--删除某个View
-(void)click:(UIButton *)btn{
    
    UIView *view = [self.view viewWithTag:btn.tag-100];
    [view removeFromSuperview];
    self.height -= view.height+10;
    
    for (int i = (int)btn.tag-100; i<self.count+10000+1; i++) {

        UIView *textView = [self.view viewWithTag:i];

        [UIView animateWithDuration:0.3 animations:^{
            textView.y -= view.height+10;
            self.footView.y = self.height+10;
        }];
        
        textView.tag-=1;
        UIButton *btn= [self.view viewWithTag:i+100];
        btn.tag = textView.tag+100;
    }
    
    self.count -=1;
    
   [self ScrollViewContSizeMake];}

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{

    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];

}

@end